<template>
	<view class="kui-w-full kui-flex kui-flex-col kui-bg-white"><slot ref="collapsePanel"></slot></view>
</template>

<script lang="ts">
/**
 * Collapse 折叠面板组件
 * @description 折叠面板容器组件
 * @property {Boolean} accordion = [true/false] 是否开启手风琴效果
 * 	@value true 是
 * 	@value false 否
 * @property {Boolean} default-expand-all = [true/false] 默认是否展开全部
 * 	value true 是
 * 	@value false 否
 */
import { reactive, getCurrentInstance, watch, onMounted, provide, nextTick, defineComponent, SetupContext } from 'vue';

const name = 'kui-collapse';

import CollapseProps from './props';

export default defineComponent({
	name,
	props: CollapseProps,
	emits: ['change', 'activeItem'],
	options: {
		// 小程序虚拟节点设置
		virtualHost: true
	},
	setup(props, context: SetupContext) {
		// 获取当前实例
		const { proxy }: any = getCurrentInstance();
		
		const data = reactive({
			modelValue: ''
		});
		
		const childrens = reactive([]);
		
		watch(
			() => data.modelValue,
			val => {
				data.modelValue = val;
			}
		);
		
		const init = () => {
			nextTick(() => {
				if (childrens) {
					childrens.forEach((vm: any, idx: number) => {
						vm.isOpen = props.defaultExpandAll ? true : false;
						if (childrens.length > 1 && childrens.length < 3) {
							vm.isBorder = idx == 0 ? true : false;
						} else if (childrens.length >= 3) {
							vm.isBorder = idx >= 0 && idx < childrens.length - 1 ? true : false;
						}
					});
				}
			});
		};
		
		onMounted(() => {
			init();
		});
		
		// 设置手风琴效果
		const setAccordion = (elId: string) => {
			nextTick(() => {
				if (childrens) {
					childrens.forEach((vm: any) => {
						if (elId !== vm.elId && props.accordion) {
							vm.isOpen = false;
						}
					});
				}
			});
		};
		
		const onChange = () => {
			let activeItem: any = [];
			nextTick(() => {
				if (childrens) {
					childrens.forEach((vm: any, idx: number) => {
						if (vm.isOpen) {
							let item = vm.name ? vm.name : idx;
							activeItem.push(item);
						}
					});
					context.emit('change', activeItem);
				} else {
					console.warn('kui-collapse:kui-collapse-panel init error');
				}
			})
		};
		
		provide('collapse', {
			setAccordion,
			onChange,
			childrens
		});
	}
});
</script>

<style></style>
